//
//  KLOpenClockViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/4/25.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLOpenClockViewController.h"
#import "NSString+Hex.h"
#import "NSData+hex.h"
#import "KLHelp.h"
#import "KLHttpAPI.h"
#import "DeformationButton.h"
#import "HemaConst.h"
#import "MMDrawerBarButtonItem.h"
#import "UIViewController+MMDrawerController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "KLpicLabel.h"
#import "HemaFunction.h"
#import "RSA_C.h"
#import "AES128EBC_No_Padding_Unit.h"
#import "NSData+hex.h"
#import "JRToast.h"
#import "UIView+i7Rotate360.h"
#import "Masonry.h"
#import "KLSettingTableViewController.h"
#import "KLRBSettingTableViewController.h" // 新需求
#import "KLMyLockTableViewController.h"
#import "KLSendKeyTableViewController.h"
#import "KLApplyForKeyViewController.h"
#import "KLImplementCommondsTableViewController.h"
#import "KLMyWalletTableViewController.h"
#import "UIAlertView+Blocks.h"
#import "UIImageView+WebCache.h"
#import "KLManualTableViewController.h"
#import "SSKeychain.h"
#import "KLKeyTypeSelectTableViewController.h"
#import "MBProgressHUDManager.h"
#import "AZNotification.h"
#import "AZNotificationView.h"
#import "KLMessageTableViewController.h"
#import "KLTabBarVC.h"

static NSInteger inshju = 0;

static BOOL isOpenBlueTooth;
@interface KLOpenClockViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate,UIAlertViewDelegate>
{
    CBCentralManager *manager;
    CBPeripheral *_peripheral;
    
    
    BOOL isManaulOpen;//判断是不是自动开锁
    BOOL isFirst; //判断第一次还是第二次返回的数据
    NSData *AesKey;//从锁内拿到的aes密钥
    NSString *rsaKey_or_rsaData;//当前锁主钥匙开锁的公钥或者子钥匙开锁的数据包字符串
    NSString *lockName;//锁的名字
    BOOL isMaster;//判断是不是锁主
    NSString *commondType; //让锁执行的指令类型
    NSDictionary *currentLockInfo;//执行指令的锁信息或委托命令的信息
    NSString *blackPhone;//(设置／取消)黑名单手机号
    UIView *lockDetailView;//锁详情界面视图或委托管理界面视图
    KLManualTableViewController *manualVC;//手动开锁的控制器
    
    KLpicLabel *blueStateLabel;
    
    NSDictionary *publicKeysDic; //keychain里的公钥集
    
    NSMutableArray *openLockSuccessInfo; //存开锁成功的返回信息
    
    NSString *unlockingPwd; // 开锁密码，新加功能
}

@property(nonatomic,strong)NSMutableData *backAESKeyData;//蓝牙第一次返回数据
@property(nonatomic,strong)NSMutableData *backOpenLockData;//第二次返回的数据
@property(nonatomic,strong)NSMutableArray *masterKeyArray;//锁主钥匙数组
@property(nonatomic,strong)NSMutableArray *submitKeyArray;//子钥匙数组

@property(nonatomic,strong)NSTimer *searchTimeOut;//搜索蓝牙超时
@property(nonatomic,strong)NSTimer *openTimeOut;//开锁超时

@property (nonatomic,strong) UILabel *tishiLabel; //提示用户当前开的锁的锁名

@property (nonatomic,strong) NSDictionary *currentOpenLockInfo;//当前被开的锁的锁信息字典

@property (nonatomic,strong) NSMutableArray *manaulLocks;//手动开锁搜到的蓝牙信号

@property (weak, nonatomic) IBOutlet UIImageView *lockOut;//锁外图片
@property (weak, nonatomic) IBOutlet UIImageView *lockIn;//锁内图片

@property (nonatomic,strong) NSString *hardWareVesionNum;//硬件版本号


@property (nonatomic,strong)UIImageView *keyImage;//跟随手指移动的钥匙
@property (nonatomic,assign)CGPoint lastP;//钥匙初始的中心点
@end

@implementation KLOpenClockViewController
-(NSMutableArray *)manaulLocks{
    if(!_manaulLocks){
        _manaulLocks = [NSMutableArray array];
    }
    return _manaulLocks;
}

-(NSMutableArray *)masterKeyArray{
    if(!_masterKeyArray){
        _masterKeyArray = [NSMutableArray array];
    }
    
    return _masterKeyArray;
}

-(NSMutableArray *)submitKeyArray{
    if(!_submitKeyArray){
        _submitKeyArray = [NSMutableArray array];
    }
    
    return _submitKeyArray;
}

-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
    [self hidesTabBar:NO];
    [[NSUserDefaults standardUserDefaults] setBool:true forKey:@"canShark"];
    
    //获取keychain里的所有公钥
    NSString *jsonStr = [SSKeychain passwordForService:@"com.kisslock.guoyang" account:@"publickeysdic"];
    publicKeysDic = [KLHelp dictionaryWithJsonString:jsonStr];
    
    commondType = 0;
    
    //给旧程序无版本号
    self.hardWareVesionNum = @"锁内固件版本过低";
}

-(void)viewWillDisappear:(BOOL)animated{
    [self.manaulLocks removeAllObjects];
    [[NSUserDefaults standardUserDefaults] setBool:false forKey:@"canShark"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.keyImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"yaoshi"]];
    self.keyImage.frame = CGRectMake(UI_View_Width/2-15, UI_View_Height-150, 30, 50);
    self.lastP = self.keyImage.center;
    [self.view addSubview:self.keyImage];
    UIImageView *lockHeart = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"锁芯"]];
    lockHeart.frame = CGRectMake(UI_View_Width/2-20, UI_View_Height-260, 40, 40);
    [self.view addSubview:lockHeart];
    
    //    NSLog(@"%@", NSHomeDirectory());
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UITabBarController *tabBarVC = (UITabBarController *)window.rootViewController;
    manualVC = tabBarVC.childViewControllers[1];
    openLockSuccessInfo = [NSMutableArray array];
    
    //注册所有通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushMyKeyVC:) name:@"pushMyKeyVC" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushMyLockVC:) name:@"pushMyLockVC" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushMyWalletVC:) name:@"pushMyWalletVC" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushCommondsVC:) name:@"pushCommondsVC" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applyForKeyVC:) name:@"pushApplyForKeyVC" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushSettingVC:) name:@"pushSettingVC" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkOutTime:) name:@"checkOutTime" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(settingBlackList:) name:@"settingBlackList" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cancelBlackList:) name:@"cancelBlackList" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readLockMessage:) name:@"readLockMessage" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taplockOut) name:@"shark" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeKeyCore:) name:@"changeKeyCore" object:nil]; // 跟换锁芯 2.0.0 新需求
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(unlockingPassword:) name:@"unlockingInfoNotification" object:nil]; // 开锁密码 新加
    
    //程序进入后台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterBackGround) name:@"enterBackGround" object:nil];
    
    //主界面ui设置
    [self mainUISet];
    
    if(!_backAESKeyData){
        _backAESKeyData = [[NSMutableData alloc]init];
    }
    if (!_backOpenLockData) {
        _backOpenLockData = [[NSMutableData alloc]init];
    }
    //初始化并设置委托和线程队列，最好一个线程的参数可以为nil，默认会就main线程
    manager =  [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    self.manualManager = manager;
}

#pragma mark- 蓝牙相关
//监听蓝牙状态
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
        case 0:
            NSLog(@"初始化中，请稍后……");
            blueStateLabel.textLabel.text = @"蓝牙尚未开启!";
            break;
        case 1:
            NSLog(@"设备不支持状态，过会请重试……");
            blueStateLabel.textLabel.text = @"蓝牙尚未开启!";
            isOpenBlueTooth = false;
            break;
        case 2:
            NSLog(@"设备未授权状态，过会请重试……");
            blueStateLabel.textLabel.text = @"蓝牙尚未开启!";
            isOpenBlueTooth = false;
            break;
        case 3:
            NSLog(@"设备未授权状态，过会请重试……");
            blueStateLabel.textLabel.text = @"蓝牙尚未开启!";
            isOpenBlueTooth = false;
            break;
        case 4:
            NSLog(@"尚未打开蓝牙，请在设置中打开……");
            blueStateLabel.textLabel.text = @"蓝牙尚未开启!";
            isOpenBlueTooth = false;
            break;
        case 5:
            NSLog(@"蓝牙已经成功开启，稍后……");
            blueStateLabel.textLabel.text = @"蓝牙已经开启!";
            isOpenBlueTooth = true;
            break;
        default:
            break;
    }
}

//扫描到设备会进入方法
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    _peripheral = peripheral;
    lockName = peripheral.name;
    NSLog(@"扫描到设备:%@，RSSI = %zd,isManaulOpen:%zd",peripheral.name,RSSI.integerValue,isManaulOpen);
    if(isManaulOpen){
        if([RSSI floatValue] >= -95 && [self manaulIsHavekeyWithPeripheral:peripheral]){
            BOOL isRepeat = false;
            for (CBPeripheral *per in self.manaulLocks) {
                if([per.name isEqualToString:peripheral.name]){
                    isRepeat = true;
                    break;
                }
            }
            if(!isRepeat){
                [self.manaulLocks addObject:peripheral];
            }
            isRepeat = false;
            NSDictionary *manualPerArr = [NSDictionary dictionaryWithObject:self.manaulLocks forKey:@"manaulLocks"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"manual" object:nil userInfo:manualPerArr];
        }
        
        return ;
    }
    
    //只检查Kiss开头的设备
    if(commondType.integerValue == 0){
        //开锁
        if ([RSSI floatValue] >= -77 && [peripheral.name hasPrefix:@"Kiss"] && [self findKey]){
            //给提示label赋值
            self.tishiLabel.text = [NSString stringWithFormat:@"正在开%@锁",lockName];
            //同时搜到钥匙即连接
            [manager connectPeripheral:peripheral options:0];
            [manager stopScan];
        }
    }
    else if(commondType.integerValue == 1){
        //扫描到要连的设备即取消搜索超时并且停止扫描
        //校时
        if([peripheral.name isEqualToString:[currentLockInfo objectForKey:@"uname"]]){
            _peripheral = peripheral;
            [manager connectPeripheral:peripheral options:0];
            [manager stopScan];
        }
    }
    else if (commondType.integerValue == 2){
        //扫描到要连的设备即取消搜索超时并且停止扫描
        //设置黑名单
        if([peripheral.name isEqualToString:[currentLockInfo objectForKey:@"uname"]]){
            _peripheral = peripheral;
            [manager connectPeripheral:peripheral options:0];
            [manager stopScan];
        }
    }
    else if (commondType.integerValue == 3){
        //取消黑名单
        if([peripheral.name isEqualToString:[currentLockInfo objectForKey:@"uname"]]){
            _peripheral = peripheral;
            [manager connectPeripheral:peripheral options:0];
            [manager stopScan];
        }
    }
    else if (commondType.integerValue == 4){
        //读取锁信息
        if([peripheral.name isEqualToString:[currentLockInfo objectForKey:@"uname"]]){
            _peripheral = peripheral;
            [manager connectPeripheral:peripheral options:0];
            [manager stopScan];
        }
    }
    else if (commondType.integerValue == 5) {
        // 锁主更换锁芯
        if ([peripheral.name isEqualToString:[currentLockInfo objectForKey:@"uname"]]) {
            _peripheral = peripheral;
            [manager connectPeripheral:peripheral options:0];
            [manager stopScan];
        }
    }
    // 设置 开锁密码
    else if (commondType.integerValue == 6) {
        if ([peripheral.name isEqualToString:[currentLockInfo objectForKey:@"uname"]]) {
            _peripheral = peripheral;
            [manager connectPeripheral:peripheral options:0];
            [manager stopScan];
        }
    }
}

//连接到Peripherals-失败
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@">>>连接到名称为（%@）的设备-失败,原因:%@",[peripheral name],[error localizedDescription]);
    [KLHelp showTextHUDforView:[UIApplication sharedApplication].keyWindow text:@"与锁建立连接失败！"];
    if(lockDetailView != nil){
        [KLHelp hideAllHUDsForView:lockDetailView animated:YES];
    }
    [self.searchTimeOut invalidate];
    [self stop720Animation];
    [[NSUserDefaults standardUserDefaults] setBool:true forKey:@"canShark"];
}

//连接到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    [JRToast showWithText:@"蓝牙连接成功" bottomOffset:UI_View_Height/3 duration:1.5];
    //连上设备即取消搜索超时并且停止扫描
    [self.searchTimeOut invalidate];
    self.searchTimeOut = nil;
    //开启开锁定时
    self.openTimeOut = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(openTimeOut:) userInfo:nil repeats:NO];
    [_peripheral setDelegate:self];
    [_peripheral discoverServices:nil];
}

//扫描到Services
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    for (CBService *service in _peripheral.services) {
        CBUUID *uid = [CBUUID UUIDWithString:@"FFF0"];
        if([service.UUID isEqual:uid]){
            [_peripheral discoverCharacteristics:nil forService:service];
        }
    }
}

//扫描到Characteristics
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    for (CBCharacteristic *characteristic in service.characteristics){
        
        CBUUID *uid = [CBUUID UUIDWithString:@"0xFFF6"];
        if ([characteristic.UUID isEqual:uid]){
            //监听特征
            [_peripheral setNotifyValue:YES forCharacteristic:characteristic];
            NSString *responseFlag = [NSString stringWithFormat:@"%lx",(unsigned long)characteristic.properties];
            [[NSUserDefaults standardUserDefaults]setObject:responseFlag forKey:@"responseFlag"];
            NSLog(@"开始通讯");
            //            if(commondType.integerValue != 0){
            //                [KLHelp showHUDAddedTo:[KLTabBarVC sharedTabBarVC].selectedViewController.view animated:YES];
            //            }
            //执行拿到aeskey
            [BuleFuction doGetAESKeywith:peripheral and:characteristic];
            
            [_backAESKeyData setLength:0];//置空
            isFirst = YES;
            self.tishiLabel.text = @"检查外围数据...";
        }
    }
}

//获取的charateristic的值
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    MBProgressHUDManager *HUDManager = [[MBProgressHUDManager alloc] initWithView:[UIApplication sharedApplication].keyWindow];
    if (isFirst){
        //第一次返回的数据
        [_backAESKeyData appendData:characteristic.value];
        NSLog(@"_backAESKeyData:%@",_backAESKeyData);
        if(_backAESKeyData.length == 26){
            [AZNotification showNotificationWithTitle:@"外围数据RSA加密故障" controller:[KLTabBarVC sharedTabBarVC].selectedViewController notificationType:AZNotificationTypeError];
            [self stop720Animation];
            [manager cancelPeripheralConnection:peripheral];
            [_backAESKeyData setLength:0];//置空
            return ;
        }
        
        if (_backAESKeyData.length>150){
            NSLog(@"返回的AES数据总长度:%zd",_backAESKeyData.length);
            //开锁定时取消
            [self.openTimeOut invalidate];
            //开启开锁定时
            self.openTimeOut = [NSTimer scheduledTimerWithTimeInterval:12 target:self selector:@selector(openTimeOut:) userInfo:nil repeats:NO];
            
            //返回的RSA加密后的AES密钥（NSData）
            NSData *aesData = [_backAESKeyData subdataWithRange:NSMakeRange(23, 128)];
            //得到解密后的AES密钥
            NSData *firstData = [RSA_C decryptData:aesData privateKey:PRRIVATES];
            if(firstData.length > 16){
                NSData *hardVesionData = [firstData subdataWithRange:NSMakeRange(16, 4)];
                self.hardWareVesionNum = [hardVesionData convertDataToHexStr:hardVesionData];
            }
            NSLog(@"解密后的firstData:%@,长度:%zd",firstData,firstData.length);
            if(firstData.length == 15 || firstData.length == 39){
                //执行拿到aeskey
                [BuleFuction doGetAESKeywith:peripheral and:characteristic];
                [_backAESKeyData setLength:0];//置空
                NSLog(@"数据丢失，正在重开！");
                return ;
            }
            
            AesKey = [firstData subdataWithRange:NSMakeRange(0, 16)];
            _peripheral.delegate = self;
            if(commondType.integerValue == 0){
                //发送开锁指令包
                NSLog(@"当前发送的公钥或数据包为:%@,长度为:%zd,锁名为:%@",rsaKey_or_rsaData,rsaKey_or_rsaData.length,lockName);
                if (isMaster == false) {
                    NSLog(@"%@-------",self.currentOpenLockInfo);
                    NSString *aesPackage = [self.currentOpenLockInfo objectForKey:@"AES_encrpt_data"];
                    //子钥匙
                    [BuleFuction accreditDoOpenLock:AesKey andPrigher:peripheral and:characteristic withData:[rsaKey_or_rsaData convertHexStrToData:rsaKey_or_rsaData] lastAESPackage:[aesPackage convertHexStrToData:aesPackage]];
                }else{
                    //锁主钥匙
                    [BuleFuction doOpenLock:AesKey andPrigher:peripheral and:characteristic withRSApublickeKey:rsaKey_or_rsaData];
                }
                isFirst = NO;
                [_backOpenLockData setLength:0];
                inshju = 0;
            }
            else if(commondType.integerValue == 1){
                NSString *code = [currentLockInfo objectForKey:@"RSA_data"];
                if(code == nil){
                    NSLog(@"锁主校时");
                    //锁主发送校时指令包
                    [BuleFuction checkoutTime:AesKey andPrigher:_peripheral and:characteristic withRSApublickeKey:[publicKeysDic objectForKey:[currentLockInfo objectForKey:@"uname"]]];
                }else{
                    NSString *aesPackage = [currentLockInfo objectForKey:@"AES_data"];
                    NSLog(@"委托校时");
                    //委托发送校时指令包
                    [BuleFuction accreditDoCheckTime:AesKey andPrigher:_peripheral and:characteristic withData:[code convertHexStrToData:code] lastAESPackage:[aesPackage convertHexStrToData:aesPackage]];
                }
                isFirst = NO;
                [_backOpenLockData setLength:0];
                NSLog(@"发送校时指令包");
            }
            else if(commondType.integerValue == 2){
                NSString *code = [currentLockInfo objectForKey:@"RSA_data"];
                if(code == nil){
                    //锁主发送设置黑名单指令包
                    [BuleFuction settingBlackList:AesKey andPrigher:_peripheral and:characteristic withRSApublickeKey:[publicKeysDic objectForKey:[currentLockInfo objectForKey:@"uname"]] blackMobile:blackPhone];
                }else{
                    NSString *aesPackage = [currentLockInfo objectForKey:@"AES_data"];
                    //委托发送设置黑名单指令包
                    [BuleFuction accreditDoSettingBlackUser:AesKey andPrigher:_peripheral and:characteristic withData:[code convertHexStrToData:code] lastAESPackage:[aesPackage convertHexStrToData:aesPackage]];
                }
                isFirst = NO;
                [_backOpenLockData setLength:0];
                NSLog(@"发送设置黑名单指令包");
            }
            else if (commondType.integerValue == 3){
                NSString *code = [currentLockInfo objectForKey:@"RSA_data"];
                if(code == nil){
                    //锁主发送取消黑名单指令包
                    [BuleFuction cancelBlackList:AesKey andPrigher:_peripheral and:characteristic withRSApublickeKey:[publicKeysDic objectForKey:[currentLockInfo objectForKey:@"uname"]] blackMobile:blackPhone];
                }else{
                    NSString *aesPackage = [currentLockInfo objectForKey:@"AES_data"];
                    [BuleFuction accreditDoCancelBlackUser:AesKey andPrigher:_peripheral and:characteristic withData:[code convertHexStrToData:code] lastAESPackage:[aesPackage convertHexStrToData:aesPackage]];
                }
                isFirst = NO;
                [_backOpenLockData setLength:0];
                NSLog(@"发送取消黑名单指令包");
            }
            else if (commondType.integerValue == 4){
                //锁主发送读取锁信息指令包
                [BuleFuction readLockMessage:AesKey andPrigher:_peripheral and:characteristic withRSApublickeKey:[publicKeysDic objectForKey:[currentLockInfo objectForKey:@"uname"]]];
                isFirst = NO;
                [_backOpenLockData setLength:0];
                NSLog(@"发送读取锁信息指令包");
            }
            else if (commondType.integerValue == 5) {
                NSLog(@"发送换锁芯指令包");
                //锁主发送 更换锁芯指令包
                [BuleFuction changeLockCore:AesKey andPeripheral:_peripheral andCharacteristic:characteristic andRSAPublicKey:[publicKeysDic objectForKey:[currentLockInfo objectForKey:@"uname"]]];
                isFirst = NO;
                [_backOpenLockData setLength:0];
            }
            else if (commondType.integerValue == 6) {
                NSLog(@"发送 设置密码指令包");
                // 设置密码，
                [BuleFuction settingPassword:AesKey andPeripheral:_peripheral and:characteristic withRSApublickeKey:[publicKeysDic objectForKey:[currentLockInfo objectForKey:@"uname"]] password:unlockingPwd];
                
            }
            self.tishiLabel.text = @"检查核心数据...";
        }
        
    }else{
        //第二包返回的数据包
        [_backOpenLockData appendData:characteristic.value];
        if(commondType.integerValue == 0){
            inshju += 1;
        }
        NSLog(@"========:characteristic.value：%@,长度：%zd,计数:%zd",characteristic.value,characteristic.value.length,inshju);
        if(inshju == 1){
            NSString *error112233445566 = [characteristic.value convertDataToHexStr:characteristic.value];
            if([error112233445566 isEqualToString:@"112233445566"]){
                [manager cancelPeripheralConnection:peripheral];
                [self stop720Animation];
                [HUDManager showErrorWithMessage:@"通信故障，请尝试重新开锁"];
            }
        }
        if(inshju > 5 && inshju < 96){
            [self saveOpenLockSuccessBackInformation:characteristic.value];
        }
        
        NSLog(@"第二次返回数据长度:%zd",_backOpenLockData.length);
        if(_backOpenLockData.length == 26){
            NSString *backOpenLockStr = [_backOpenLockData convertDataToHexStr:_backOpenLockData];
            NSString *subStr = [backOpenLockStr substringWithRange:NSMakeRange(46, 2)];
            if([subStr isEqualToString:@"25"]){
                [AZNotification showNotificationWithTitle:@"核心数据RSA加密故障" controller:[KLTabBarVC sharedTabBarVC].selectedViewController notificationType:AZNotificationTypeError];
                [self stop720Animation];
                [manager cancelPeripheralConnection:peripheral];
                return ;
            }else if ([subStr isEqualToString:@"26"]){
                [AZNotification showNotificationWithTitle:@"您已被设为黑名单" controller:[KLTabBarVC sharedTabBarVC].selectedViewController notificationType:AZNotificationTypeError];
                [self stop720Animation];
                [manager cancelPeripheralConnection:peripheral];
                return ;
            }
        }
        
        //开锁返回数据
        if (commondType.integerValue == 0 && (_backOpenLockData.length == 57|| _backOpenLockData.length == 26)){
            dispatch_time_t time=dispatch_time(DISPATCH_TIME_NOW, 3ull *NSEC_PER_SEC);
            dispatch_after(time, dispatch_get_main_queue(), ^{
                //上传锁返回信息
                [KLHttpAPI uploadLockBackInfoToServer:openLockSuccessInfo completionHandler:^(NSDictionary *responseDic){
                    NSString *isSuccess = [responseDic objectForKey:@"success"];
                    if(isSuccess.integerValue == 1){
                        NSLog(@"锁记录上传成功!");
                    }
                } errorHandler:^(NSString *error) {
                }];
                inshju = 0;
                [manager cancelPeripheralConnection:peripheral];
                [openLockSuccessInfo removeAllObjects];
            });
            NSData *markData = [_backOpenLockData subdataWithRange:NSMakeRange(23, 32)];
            NSLog(@"markData:%@",markData);
            NSData *deeDAta = [AES128EBC_No_Padding_Unit AES128Decrypt:markData withAESKey:AesKey];
            NSLog(@"解密后的数据:%@",deeDAta);
            
            NSMutableData *backMuData = [[NSMutableData alloc]initWithData:deeDAta];
            NSData *backData = [backMuData subdataWithRange:NSMakeRange(0, 1)];
            //检查数据的开头
            Byte markByte0[1];
            markByte0[0] = 0x00;
            Byte markByte2[1];
            markByte2[0] = 0x12;
            Byte markByte3[1];
            markByte3[0] = 0x13;
            Byte markByte4[1];
            markByte4[0] = 0x14;
            if ([backData isEqual:[NSData dataWithBytes:markByte0 length:1]]){
                //以00开头即返回成功
                [HUDManager showSuccessWithMessage:@"开锁成功" duration:3];
                [self stop720Animation];
                //给服务器上传锁返回信息
                [self saveLockBackInformationForDictionary:deeDAta];
            }else if ([backData isEqual:[NSData dataWithBytes:markByte2 length:1]]){
                //以12开头即返回成功
                [JRToast showWithText:@"非授权用户"];
                [self stop720Animation];
                //给服务器上传锁返回信息
                [self saveLockBackInformationForDictionary:deeDAta];
            }else if ([backData isEqual:[NSData dataWithBytes:markByte3 length:1]]){
                //以13开头即返回成功
                [JRToast showWithText:@"非授权开锁时间"];
                [self stop720Animation];
                //给服务器上传锁返回信息
                [self saveLockBackInformationForDictionary:deeDAta];
            }else if ([backData isEqual:[NSData dataWithBytes:markByte4 length:1]]){
                //以14开头即返回成功
                [JRToast showWithText:@"钥匙过期"];
                [self stop720Animation];
                //给服务器上传锁返回信息
                [self saveLockBackInformationForDictionary:deeDAta];
            }else{
                [JRToast showWithText:@"开锁错误,请重试"];
                [self stop720Animation];
            }
            
            // 锁厂锁返回开锁信息处理
            [self messageOfTroubleData:backData deeData:deeDAta];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"openLockComplete" object:nil userInfo:nil];
        }
        
        
        //校时返回数据
        else if(commondType.integerValue == 1 && _backOpenLockData.length > 25){
            [KLHelp hideAllHUDsForView:lockDetailView animated:YES];
            NSLog(@"_backOpenLockData:%@",_backOpenLockData);
            NSData *markData = [_backOpenLockData subdataWithRange:NSMakeRange(23, 1)];
            NSLog(@"markData:%@",markData);
            //检查数据的开头
            Byte markByte0[1];
            markByte0[0] = 0x50;//指令正常
            Byte markByte2[1];
            markByte2[0] = 0x51;//指令过期
            Byte markByte3[1];
            markByte3[0] = 0x52;//指令序号过期
            if([markData isEqual:[NSData dataWithBytes:markByte0 length:1]]){
                [HUDManager showSuccessWithMessage:@"校时成功" duration:1.5];
                if ([[currentLockInfo allKeys] count] < 20) {
                    [KLHttpAPI implementCommondSuccessWithCommondId:[currentLockInfo objectForKey:@"id"] completionHandler:^(MKNetworkOperation *operation) {
                        NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
                        if(isSuccess.integerValue == 1){
                            NSLog(@"委托执行成功:%@",operation.responseString);
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshCommand" object:nil];
                        }
                    } errorHandler:^(NSString *error) {
                    }];
                }
            }else if([markData isEqual:[NSData dataWithBytes:markByte2 length:1]]){
                [HUDManager showErrorWithMessage:@"指令过期,校时失败"];
            }else if([markData isEqual:[NSData dataWithBytes:markByte3 length:1]]){
                [HUDManager showErrorWithMessage:@"指令序号过期,校时失败"];
            }else{
                [JRToast showWithText:@"哈哈哈哈😆"];
            }
            
            [manager cancelPeripheralConnection:peripheral];
        }
        //设置黑名单返回数据
        else if(commondType.integerValue == 2 && _backOpenLockData.length > 25){
            [KLHelp hideAllHUDsForView:lockDetailView animated:YES];
            NSData *markData = [_backOpenLockData subdataWithRange:NSMakeRange(23, 1)];
            NSLog(@"markData:%@",markData);
            //检查数据的开头
            Byte markByte0[1];
            markByte0[0] = 0x50;//指令正常
            Byte markByte2[1];
            markByte2[0] = 0x51;//指令过期
            Byte markByte3[1];
            markByte3[0] = 0x52;//指令序号过期
            if([markData isEqual:[NSData dataWithBytes:markByte0 length:1]]){
                [HUDManager showSuccessWithMessage:@"设置成功" duration:1.5];
                if ([[currentLockInfo allKeys] count] < 20) {
                    [KLHttpAPI implementCommondSuccessWithCommondId:[currentLockInfo objectForKey:@"id"] completionHandler:^(MKNetworkOperation *operation) {
                        NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
                        if(isSuccess.integerValue == 1){
                            NSLog(@"委托执行成功:%@",operation.responseString);
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshCommand" object:nil];
                        }
                    } errorHandler:^(NSString *error) {
                    }];
                }
            }else if([markData isEqual:[NSData dataWithBytes:markByte2 length:1]]){
                [HUDManager showErrorWithMessage:@"指令过期,设置失败"];
            }else if([markData isEqual:[NSData dataWithBytes:markByte3 length:1]]){
                [HUDManager showErrorWithMessage:@"指令序号过期,设置失败"];
            }else{
                [HUDManager showErrorWithMessage:[NSString stringWithFormat:@"未知错误：%@",markData]];
            }
            
            [manager cancelPeripheralConnection:peripheral];
        }
        //取消黑名单返回数据
        else if(commondType.integerValue == 3 && _backOpenLockData.length > 25){
            [KLHelp hideAllHUDsForView:lockDetailView animated:YES];
            NSData *markData = [_backOpenLockData subdataWithRange:NSMakeRange(23, 1)];
            NSLog(@"markData:%@",markData);
            //检查数据的开头
            Byte markByte0[1];
            markByte0[0] = 0x50;//指令正常
            Byte markByte2[1];
            markByte2[0] = 0x51;//指令过期
            Byte markByte3[1];
            markByte3[0] = 0x52;//指令序号过期
            if([markData isEqual:[NSData dataWithBytes:markByte0 length:1]]){
                [HUDManager showSuccessWithMessage:@"取消成功" duration:1.5];
                if ([[currentLockInfo allKeys] count] < 20) {
                    [KLHttpAPI implementCommondSuccessWithCommondId:[currentLockInfo objectForKey:@"id"] completionHandler:^(MKNetworkOperation *operation) {
                        NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
                        if(isSuccess.integerValue == 1){
                            NSLog(@"委托执行成功:%@",operation.responseString);
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshCommand" object:nil];
                        }
                    } errorHandler:^(NSString *error) {
                    }];
                }
            }else if([markData isEqual:[NSData dataWithBytes:markByte2 length:1]]){
                [HUDManager showErrorWithMessage:@"指令过期,设置失败"];
            }else if([markData isEqual:[NSData dataWithBytes:markByte3 length:1]]){
                [HUDManager showErrorWithMessage:@"指令序号过期,设置失败"];
            }else{
                [HUDManager showErrorWithMessage:[NSString stringWithFormat:@"未知错误：%@",markData]];
            }
            
            [manager cancelPeripheralConnection:peripheral];
        }
        //读取锁信息
        else if(commondType.integerValue == 4){
            NSMutableString *decryptionString = [NSMutableString string];
            NSData *endCodeData = [_backOpenLockData subdataWithRange:NSMakeRange(_backOpenLockData.length-1, 1)];
            if([[endCodeData convertDataToHexStr:endCodeData] isEqualToString:@"16"]){
                
                // 5-25 新版读取锁信息返回数据 长度都是41 bytes .判断第24 个字节如果等于07 就是锁厂的锁
                if (_backOpenLockData.length == 41) {
                    NSLog(@"_backOpenLockData:%@，长度为：%zd",_backOpenLockData,_backOpenLockData.length);
                    NSData *markData = [_backOpenLockData subdataWithRange:NSMakeRange(23,16)];
                    NSLog(@"markData:%@",markData);
                    NSData *deeDAta = [AES128EBC_No_Padding_Unit AES128Decrypt:markData withAESKey:AesKey];
                    NSLog(@"解密后的数据:%@",deeDAta);
                    NSString *dee = [deeDAta convertDataToHexStr:deeDAta];
//                    NSString *lenghtStr = [dee substringWithRange:NSMakeRange(0, 2)]; // 数据长度如果是7就是锁厂的锁
                    NSString *electrity = [dee substringWithRange:NSMakeRange(2, 2)]; // 电压数据
                    NSString *successTimes = [dee substringWithRange:NSMakeRange(4, 4)]; // 开锁成功次数
                    NSString *failTimes = [dee substringWithRange:NSMakeRange(8, 4)]; // 开锁失败次数

                    // 备注:strtoul 字符串转无符号长整数
                    UInt64 mac1 =  strtoul([electrity UTF8String], 0, 16);
                    
//                    132  %100  电量计算方法
//                    0    %0
                    UInt64 elec = ( mac1 / 132.0 *100);
                    if (elec >= 100) {
                        electrity = [NSString stringWithFormat:@"100%%"];
                    }else {
                        electrity = [NSString stringWithFormat:@"%llu%@",elec,@"%"];
                    }

                    UInt64 mac2 =  strtoul([successTimes UTF8String], 0, 16);
                    UInt64 mac3 =  strtoul([failTimes UTF8String], 0, 16);
                    
                    NSString *lockMsgString = [NSString stringWithFormat:@"电压:%@ 开锁成功次数:%llu 开锁失败次数:%llu",electrity,mac2,mac3];
                    
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"读取到的锁内信息" message:lockMsgString delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    [alert show];
                  
                    [manager cancelPeripheralConnection:peripheral];

                }
                
                
                
                
                // 返回数据大于 50 字节长度:正常流程
                if (_backOpenLockData.length > 42){
                    
                    [KLHelp hideAllHUDsForView:lockDetailView animated:YES];
                    NSLog(@"_backOpenLockData:%@，长度为：%zd",_backOpenLockData,_backOpenLockData.length);
                    NSData *markData = [_backOpenLockData subdataWithRange:NSMakeRange(23,16)];
                    NSLog(@"markData:%@",markData);
                    NSData *deeDAta = [AES128EBC_No_Padding_Unit AES128Decrypt:markData withAESKey:AesKey];
                    NSLog(@"解密后的数据:%@",deeDAta);
                    NSString *dee = [deeDAta convertDataToHexStr:deeDAta];
                    // 通过convertDataToHexStr:该方法转换后的 2 * Data.lenght = NSString.length
                    
                    NSString *electrity = [dee substringWithRange:NSMakeRange(2, 2)]; // 电压数据
                    NSString *successTimes = [dee substringWithRange:NSMakeRange(4, 4)]; // 开锁成功次数
                    NSString *failTimes = [dee substringWithRange:NSMakeRange(8, 4)];
                    NSString *blackNameCount = [dee substringWithRange:NSMakeRange(16, 2)];
                    NSLog(@"被设置的黑名单个数:%zd",blackNameCount.integerValue);
                    
                    // 备注:strtoul 字符串转无符号长整数
                    UInt64 mac1 =  strtoul([electrity UTF8String], 0, 16);
                    UInt64 mac2 =  strtoul([successTimes UTF8String], 0, 16);
                    UInt64 mac3 =  strtoul([failTimes UTF8String], 0, 16);
                    if(mac1/40.f > 5.6){
                        electrity = @"100%";
                    }else if (mac1/40.f > 4.8){
                        electrity = @"80%";
                    }else if (mac1/40.f >4.6){
                        electrity = @"50%";
                    }else if (mac1/40.f > 4.0){
                        electrity = @"30%";
                    }else{
                        electrity = @"10%";
                    }
                    [decryptionString appendString:dee];
                    
                    //检查有多少段加密数据
                    unsigned long encryptionNumber = (_backOpenLockData.length-25)/16;
                    //解密黑名单个数
                    for (int i = 1; i < encryptionNumber; i++) {
                        NSData *markData_sub = [_backOpenLockData subdataWithRange:NSMakeRange(23+16*i,16)];
                        NSLog(@"markData_sub:%@",markData);
                        NSData *deeDAta_sub = [AES128EBC_No_Padding_Unit AES128Decrypt:markData_sub withAESKey:AesKey];
                        NSLog(@"解密后的数据_sub:%@",deeDAta_sub);
                        NSString *dee_sub = [deeDAta_sub convertDataToHexStr:deeDAta_sub];
                        [decryptionString appendString:dee_sub];
                    }
                    NSLog(@"总数据字符串:%@",decryptionString);
                    NSMutableArray *blackNamesArr = [NSMutableArray array];
                    NSString *blackNames = [decryptionString substringFromIndex:18];
                    for (int i = 0; i < blackNames.length/2; i++) {
                        if(i != 0 && (i+1)%12 == 0) continue;
                        [blackNamesArr addObject:[blackNames substringWithRange:NSMakeRange(i*2, 2)]];
                    }
                    //截成只有手机号连手机号的字符串
                    NSMutableString *mobileByMobile = [NSMutableString string];
                    for (NSString *number in blackNamesArr) {
                        [mobileByMobile appendFormat:@"%zd",number.integerValue];
                    }
                    NSLog(@"手机号连手机号:%@",mobileByMobile);
                    NSMutableString *mobileToUser = [NSMutableString string];
                    for (int i = 0; i < mobileByMobile.length/11; i++) {
                        NSString *subMobile = [mobileByMobile substringWithRange:NSMakeRange(i*11, 11)];
                        if([subMobile isEqualToString:@"00000000000"]) continue;
                        [mobileToUser appendFormat:@"%@  ",subMobile];
                    }
                    NSLog(@"mobileByMobile:%@",mobileByMobile);
                    //没有设黑名单时数组里会有7个0
                    if([mobileByMobile isEqualToString:@"0000000"]){
                        mobileToUser = [NSMutableString stringWithString:@"无"];
                    }
                    
                    NSString *result = [NSString stringWithFormat:@"电量:%@,开锁成功次数:%llu,开锁失败次数:%llu,黑名单:%@",electrity,mac2,mac3,mobileToUser];
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"读取到的锁内信息" message:result delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    [alert show];
                    NSLog(@"电量:%llu,开锁成功次数:%llu,开锁失败次数:%llu",mac1,mac2,mac3);
                    
                    [manager cancelPeripheralConnection:peripheral];
                    
                }
                else { //这个是新版的，如果回复数据为0x9C，你就判断数据长度这个字节是否为7，为7 就是和锁厂合作的锁，你就把电压值后面的数据解析为时间就行了，不为7就还是和以前一样
                    
                    NSData *markData = [_backOpenLockData subdataWithRange:NSMakeRange(23,16)];
                    NSLog(@"markData:%@",markData);
                    NSData *deeDAta = [AES128EBC_No_Padding_Unit AES128Decrypt:markData withAESKey:AesKey];
                    NSLog(@"解密后的数据:%@",deeDAta);
                    
                    NSString *dee = [deeDAta convertDataToHexStr:deeDAta];
                    // 通过convertDataToHexStr:该方法转换后的 2 * Data.lenght = NSString.length
                    
                    NSString *lengthStr = [dee substringWithRange:NSMakeRange(0, 2)]; // 07
                    NSString *electrity = [dee substringWithRange:NSMakeRange(2, 2)]; // 电压数据
                    NSString *timeStr = [dee substringWithRange:NSMakeRange(4, 12)]; //时间
                    if ([lengthStr isEqualToString:@"07"]) {
                        UInt64 mac1 = strtoul([electrity UTF8String], 0, 16);
                        if (mac1/40.f > 5.6) {
                            electrity = @"100%";
                        }else if (mac1/40.f > 4.8){
                            electrity = @"80%";
                        }else if (mac1/40.f > 4.6){
                            electrity = @"50%";
                        }else if (mac1/4.0 > 4.0) {
                            electrity = @"30%";
                        }else {
                            electrity = @"10%";
                        }
                        
                        
                        NSString *resultStr = [NSString stringWithFormat:@"电压:%@ 时间:%@",electrity,timeStr];
                        
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"读取到的锁内信息" message:resultStr delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                        [alert show];
                        
                        [manager cancelPeripheralConnection:peripheral];
                    }
                }
                
            }
        }
        // 更换锁芯返回数据
        else if (commondType.integerValue == 5 && _backOpenLockData.length == 26) {
            NSLog(@"更换锁芯");
            NSLog(@"_backOpenLockData:%@",_backOpenLockData);
            
            NSString *backDataStr = [_backOpenLockData convertDataToHexStr:_backOpenLockData];
            NSLog(@"%@",backDataStr);
            NSString *subcmdstr = [backDataStr substringWithRange:NSMakeRange(46, 2)];
            NSLog(@"%@",subcmdstr);
            
            if ([subcmdstr isEqualToString:@"88"]) {
                [HUDManager showErrorWithMessage:@"更换锁芯成功"];
            }else {
                [HUDManager showErrorWithMessage:[NSString stringWithFormat:@"未知错误：%@",subcmdstr]];
            }
            
            [manager cancelPeripheralConnection:peripheral];
        }
        // 设置免密返回数据
        else if (commondType.integerValue == 6 && _backOpenLockData.length > 25) {
            NSLog(@"设置密码返回数据:%@",_backOpenLockData);
            [KLHelp hideAllHUDsForView:lockDetailView animated:YES];
            
            NSData *markData = [_backOpenLockData subdataWithRange:NSMakeRange(23, 1)]; // 去掉数据头23字节，的后一个字节表示表示成功或失败
            NSLog(@"markData:%@",markData);
            
            // 检查返回的数据主体
            Byte markSuccessByte[1];
            markSuccessByte[0] = 0x60; // 表示成功
            Byte markFailureByte[1];
            markFailureByte[0] = 0x61;
            
            if ([markData isEqualToData:[NSData dataWithBytes:markSuccessByte length:1]]) {
                [HUDManager showErrorWithMessage:@"设置密码成功"];
            }else if ([markData isEqualToData:[NSData dataWithBytes:markFailureByte length:1]]) {
                [HUDManager showErrorWithMessage:@"设置密码失败"];
            }
            
            [manager cancelPeripheralConnection:peripheral]; // 断开连接
        }
        
        
        [self.openTimeOut invalidate];
    }
}

-(void)openTimeOut:(NSTimer *)timer{
    [manager cancelPeripheralConnection:_peripheral];
    [AZNotification showNotificationWithTitle:@"数据无返回，尝试重新开锁！" controller:[KLTabBarVC sharedTabBarVC].selectedViewController notificationType:AZNotificationTypeWarning];
    NSLog(@"执行开锁超时");
}

//Peripherals断开连接 如果连接上的两个设备断开了，程序里面会自动回调下面的方法
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"设备连接断开:error:%@",error);
    [[NSUserDefaults standardUserDefaults] setBool:true forKey:@"canShark"];
    if(lockDetailView){
        [KLHelp hideAllHUDsForView:lockDetailView animated:YES];
    }
    lockDetailView = nil;
    [self.openTimeOut invalidate];
    //停止转动动画
    if(isManaulOpen){
        [KLHelp hideAllHUDsForView:manualVC.view animated:YES];
    }else{
        [KLHelp hideAllHUDsForView:lockDetailView animated:YES];
    }
    [self stop720Animation];
}

/***********************************************************************************************
 *                                   上面为逻辑代码下面为界面代码及工具代码                          *
 ************************************************************************************************/

#pragma mark －匹配钥匙
-(BOOL)findKey{
    rsaKey_or_rsaData = nil;
    //存入底层的锁主钥匙
    self.masterKeyArray = [[NSUserDefaults standardUserDefaults] objectForKey:MASTER_KEY_ARRAY];
    //存入底层的子钥匙
    self.submitKeyArray = [[NSUserDefaults standardUserDefaults] objectForKey:SUBMIT_KEY_ARRAY];
    
    NSLog(@"锁主钥匙集:%@",self.masterKeyArray);
    NSLog(@"子钥匙集:%@",self.submitKeyArray);
    
    //根据锁的名字去匹配钥匙
    for (NSDictionary *tmpKeyDic in self.masterKeyArray) {
        NSString *kissLockNumber = [[tmpKeyDic objectForKey:@"uname"] substringFromIndex:8];
        //锁主钥匙
        if ([lockName hasSuffix:kissLockNumber]) {
            if([publicKeysDic objectForKey:lockName] == nil){
                [JRToast showWithText:[NSString stringWithFormat:@"%@锁芯丢失",lockName]];
                [self stop720Animation];
                [self.searchTimeOut invalidate];
                return false;
            }
            rsaKey_or_rsaData = [publicKeysDic objectForKey:lockName];
            NSLog(@"锁主公钥:%@,锁名:%@",rsaKey_or_rsaData,lockName);
            self.currentOpenLockInfo = tmpKeyDic;
            isMaster = true;
            return true;
        }
    }
    
    //子钥匙信息字典
    for (NSMutableDictionary *tmpsKeyDic in self.submitKeyArray) {
        NSString *kissLockNumber = [[tmpsKeyDic objectForKey:@"uname"] substringFromIndex:8];
        //子钥匙
        if ([lockName hasSuffix:kissLockNumber]) {
            rsaKey_or_rsaData = [tmpsKeyDic objectForKey:@"key_str"];
            NSLog(@"子钥匙:%@",rsaKey_or_rsaData);
            self.currentOpenLockInfo = tmpsKeyDic;
            isMaster = false;
            return true;
        }
    }
    
    //如果rsaPublicKey为空
    if ([HemaFunction xfunc_check_strEmpty:rsaKey_or_rsaData]) {
        return false;
    }
    
    return true;
}

#pragma mark -停止转圈动画
-(void)stop720Animation{
    //停止转动动画
    [self.lockOut.layer removeAllAnimations];
    self.tishiLabel.text = @"准备开锁";
    self.lockOut.userInteractionEnabled = YES;
    lockName = nil;
    [manager stopScan];
    [UIView animateWithDuration:0.4 animations:^{
        self.keyImage.center = self.lastP;
    }];
    [[NSUserDefaults standardUserDefaults] setBool:true forKey:@"canShark"];
}

#pragma mark -主界面的UI设置
-(void)mainUISet{
    self.lockIn.layer.masksToBounds = YES;
    self.lockIn.layer.cornerRadius = 100.0f;
    self.view.backgroundColor = [KLHelp mainBlueColor];
    //    //初始化顶部广告栏
    //    [self initTheTopAdScrollView];
    //初始化左上角按钮
    [self initLeftBarButtonItem];
    //初始化右上角按钮
    [self initRightBarButtonItem];
    //设置开锁图标的位置
    [self.lockIn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).with.offset(UI_View_Height/4-20);
        make.width.mas_equalTo(UI_View_Width/10*6.7-20);
        make.height.mas_equalTo(UI_View_Width/10*6.7-20);
    }];
    [self.lockOut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.lockIn);
        make.width.mas_equalTo(UI_View_Width/10*6.7);
        make.height.mas_equalTo(UI_View_Width/10*6.7);
    }];
    
    //添加标题label
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = @"KISSLOCK";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.backgroundColor = BB_Blue_Color;
    titleLabel.font = [UIFont systemFontOfSize:23];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view).offset(0);
        make.top.mas_equalTo(42);
        make.width.mas_equalTo(UI_View_Width*0.5);
    }];
    //蓝牙状态
    blueStateLabel = [[KLpicLabel alloc]initWithFrame:CGRectZero];
    [HemaFunction addbordertoView:blueStateLabel radius:3.f width:1 color:BB_lineColor];
    [self.view addSubview:blueStateLabel];
    //    blueStateLabel.alpha = 0;
    [blueStateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.lockOut).offset(50);
        make.size.mas_equalTo(CGSizeMake(135, 30));
    }];
    //提示开的哪一把锁
    self.tishiLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    [HemaFunction addbordertoView:self.tishiLabel radius:3.f width:1 color:BB_lineColor];
    self.tishiLabel.text = @"准备开锁";
    self.tishiLabel.textColor = BB_White_Color;
    self.tishiLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.tishiLabel];
    //    self.tishiLabel.alpha = 0;
    [self.tishiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(blueStateLabel.mas_bottom).offset(20);
        make.height.mas_equalTo(32);
        make.width.mas_equalTo(230);
    }];
    
    UILabel *vesion = [[UILabel alloc]init];
    vesion.text = @"版本号:V1.8.8";
    vesion.font = [UIFont systemFontOfSize:12];
    vesion.textColor = [UIColor whiteColor];
    [self.view addSubview:vesion];
    [vesion mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).with.offset(-8);
        make.top.equalTo(self.view).with.offset(UI_View_Height/8*7);
    }];
    
    //为主界添加轻扫手势
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftDrawerButtonPress:)];
    //设置轻扫的方向
    swipeGesture.direction = UISwipeGestureRecognizerDirectionRight; //默认向右
    [self.view addGestureRecognizer:swipeGesture];
    
    //为开锁图片添加交互
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(taplockOut)];
    [self.lockOut addGestureRecognizer:tap];
}-(void)taplockOut{//点击开锁按钮执行
    [self chekBlueToothIsOpen];
    if(!isOpenBlueTooth){
        self.keyImage.center = self.lastP;
        return ;
    }
    
    [[NSUserDefaults standardUserDefaults] setBool:false forKey:@"canShark"];
    if(lockDetailView == nil){
        commondType = [NSString stringWithFormat:@"0"];
    }
    self.tishiLabel.text = @"正在搜索附近锁设备...";
    //开锁按钮不可点击
    self.lockOut.userInteractionEnabled = NO;
    //取消超时提醒
    [self.searchTimeOut invalidate];
    self.searchTimeOut = nil;
    
    //执行转圈动画
    [self.lockOut rotate360WithDuration:2 repeatCount:1000 timingMode:i7Rotate360TimingModeLinear];
    //寻找外设
    [manager scanForPeripheralsWithServices:nil options:nil];
    //开启定时器
    self.searchTimeOut = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(searchTimeOut:) userInfo:nil repeats:NO];
}-(void)searchTimeOut:(id)sender{//定时器超时
    if(lockDetailView != nil){
        [KLHelp hideAllHUDsForView:lockDetailView animated:YES];
    }
    MBProgressHUDManager *HUDManager = [[MBProgressHUDManager alloc] initWithView:[UIApplication sharedApplication].keyWindow];
    if(lockDetailView != nil){
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [HUDManager showErrorWithMessage:@"未搜到锁信号,请离锁30cm内扫描" duration:1.5];
    }else{
        if([self.tishiLabel.text hasPrefix:@"正在开"]){
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            [HUDManager showErrorWithMessage:@"建立连接失败，请稍候重试" duration:2.5];
            //            [manager cancelPeripheralConnection:_peripheral];
        }else{
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            [HUDManager showErrorWithMessage:@"未搜到锁信号,请离锁30cm内扫描" duration:2.5];
            //            [manager cancelPeripheralConnection:_peripheral];
        }
    }
    
    [manager cancelPeripheralConnection:_peripheral];
    lockDetailView = nil;
    [self stop720Animation];
}

#pragma  mark -接收通知方法
//收到推出设置界面通知
-(void)pushSettingVC:(id)sender{
    //    KLSettingTableViewController *settingVC = [[KLSettingTableViewController alloc]init];
    //    [self.navigationController pushViewController:settingVC animated:YES];
    //    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
    //    [self hidesTabBar:YES];
    
    KLRBSettingTableViewController *settingVC = [[KLRBSettingTableViewController alloc] init];
    [self.navigationController pushViewController:settingVC animated:YES];
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
    [self hidesTabBar:YES];
}

//收到推出我的锁界面通知
-(void)pushMyLockVC:(id)sender{
    KLMyLockTableViewController *myLockVC = [[KLMyLockTableViewController alloc]init];
    //    [myLockVC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:myLockVC animated:YES];
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
    [self hidesTabBar:YES];
}

//收到推出我的钱包界面通知
-(void)pushMyWalletVC:(id)sender{
    KLMyWalletTableViewController *myMyWalletVC = [[KLMyWalletTableViewController alloc]init];
    [self.navigationController pushViewController:myMyWalletVC animated:YES];
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
    [self hidesTabBar:YES];
}

//收到推出委托命令界面通知
-(void)pushCommondsVC:(id)sender{
    KLImplementCommondsTableViewController *commondsVC = [[KLImplementCommondsTableViewController alloc]init];
    [self.navigationController pushViewController:commondsVC animated:YES];
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
    [self hidesTabBar:YES];
}

//收到推出申请钥匙界面
-(void)applyForKeyVC:(id)sender{
    KLApplyForKeyViewController *applyForKeyVC = [[KLApplyForKeyViewController alloc]init];
    [self.navigationController pushViewController:applyForKeyVC animated:YES];
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
    [self hidesTabBar:YES];
}

//收到推出我的钥匙界面通知
-(void)pushMyKeyVC:(id)sender{
    KLKeyTypeSelectTableViewController *myKeyVC = [[KLKeyTypeSelectTableViewController alloc]init];
    [self.navigationController pushViewController:myKeyVC animated:YES];
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
    [self hidesTabBar:YES];
}

//收到校时通知
-(void)checkOutTime:(NSNotification *)sender{
    NSDictionary *userInfo = [sender userInfo];
    commondType = [userInfo objectForKey:@"commondType"];
    currentLockInfo = [userInfo objectForKey:@"currentLockInfo"];
    lockDetailView = [userInfo objectForKey:@"lockDetailView"];
    [KLHelp showHUDAddedTo:lockDetailView animated:YES];
    [self taplockOut];
    [manager scanForPeripheralsWithServices:nil options:nil];
}

//收到设置黑名单通知
-(void)settingBlackList:(NSNotification *)sender{
    NSDictionary *userInfo = [sender userInfo];
    commondType = [userInfo objectForKey:@"commondType"];
    currentLockInfo = [userInfo objectForKey:@"currentLockInfo"];
    blackPhone = [userInfo objectForKey:@"blackPhone"];
    lockDetailView = [userInfo objectForKey:@"lockDetailView"];
    [KLHelp showHUDAddedTo:lockDetailView animated:YES];
    [self taplockOut];
    [manager scanForPeripheralsWithServices:nil options:nil];
}

//收到取消黑名单通知
-(void)cancelBlackList:(NSNotification *)sender{
    NSDictionary *userInfo = [sender userInfo];
    commondType = [userInfo objectForKey:@"commondType"];
    currentLockInfo = [userInfo objectForKey:@"currentLockInfo"];
    blackPhone = [userInfo objectForKey:@"blackPhone"];
    lockDetailView = [userInfo objectForKey:@"lockDetailView"];
    [KLHelp showHUDAddedTo:lockDetailView animated:YES];
    [self taplockOut];
    [manager scanForPeripheralsWithServices:nil options:nil];
}

//读取锁信息
-(void)readLockMessage:(NSNotification *)sender{
    NSDictionary *userInfo = [sender userInfo];
    commondType = [userInfo objectForKey:@"commondType"];
    currentLockInfo = [userInfo objectForKey:@"currentLockInfo"];
    lockDetailView = [userInfo objectForKey:@"lockDetailView"];
    [KLHelp showHUDAddedTo:lockDetailView animated:YES];
    [self taplockOut];
    [manager scanForPeripheralsWithServices:nil options:nil];
}

// 锁主 更换锁芯 2.0.0 新增
- (void)changeKeyCore:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    commondType = [userInfo objectForKey:@"commondType"];
    currentLockInfo = [userInfo objectForKey:@"currentLockInfo"];
    lockDetailView = [userInfo objectForKey:@"lockDetailView"];
    [KLHelp showHUDAddedTo:lockDetailView animated:YES];
    [self taplockOut];
    [manager scanForPeripheralsWithServices:nil options:nil];
}

/**设置密码 新加*/
- (void)unlockingPassword:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    
    commondType = [userInfo objectForKey:@"commondType"];
    currentLockInfo = [userInfo objectForKey:@"currentLockInfo"];
    lockDetailView = [userInfo objectForKey:@"lockDetailView"];
    unlockingPwd = [userInfo objectForKey:@"unlockingPassword"];
    [KLHelp showHUDAddedTo:lockDetailView animated:YES];
    [self taplockOut];
    [manager scanForPeripheralsWithServices:nil options:nil];
}

-(void)appEnterBackGround{
    [self stop720Animation];
    if(manager != nil && _peripheral != nil){
        [manager cancelPeripheralConnection:_peripheral];
    }
    NSLog(@"进入后台，断开蓝牙");
}

#pragma mark -上传开锁信息
-(void)saveLockBackInformationForDictionary:(NSData *)deeData{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //锁返回字符串
    NSString *deeDataStr = [deeData convertDataToHexStr:deeData];
    NSString *lockTime = [deeDataStr substringWithRange:NSMakeRange(26, 12)];
    NSLog(@"lockTime:%@",lockTime);
    NSString *showTime = [NSString stringWithFormat:@"20%@",lockTime];
    
    NSDateFormatter *strToDateFmt = [[NSDateFormatter alloc] init];
    [strToDateFmt setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *outputDate = [strToDateFmt dateFromString:showTime];
    NSDateFormatter *dateToStrFmt = [[NSDateFormatter alloc]init];
    [dateToStrFmt setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *outputStr = [dateToStrFmt stringFromDate:outputDate];
    if(isManaulOpen){
        if(outputStr == NULL){
            outputStr = @"时间乱码，无法解析，请校时！";
            [AZNotification showNotificationWithTitle:[NSString stringWithFormat:@"当前锁内时间：%@\n固件版本号：%@",outputStr,self.hardWareVesionNum] controller:[KLTabBarVC sharedTabBarVC].selectedViewController notificationType:AZNotificationTypeWarning];
        }else{
            [AZNotification showNotificationWithTitle:[NSString stringWithFormat:@"当前锁内时间：%@\n固件版本号：%@",outputStr,self.hardWareVesionNum] controller:[KLTabBarVC sharedTabBarVC].selectedViewController notificationType:AZNotificationTypeSuccess];
        }
    }else{
        if(outputStr == NULL){
            outputStr = @"时间乱码，无法解析，请校时！";
            [AZNotification showNotificationWithTitle:[NSString stringWithFormat:@"当前锁内时间：%@\n固件版本号：%@",outputStr,self.hardWareVesionNum] controller:[KLTabBarVC sharedTabBarVC].selectedViewController notificationType:AZNotificationTypeWarning];
        }else{
            [AZNotification showNotificationWithTitle:[NSString stringWithFormat:@"当前锁内时间：%@\n固件版本号：%@",outputStr,self.hardWareVesionNum] controller:[KLTabBarVC sharedTabBarVC].selectedViewController notificationType:AZNotificationTypeSuccess];
        }
    }
    
    //用户手机号
    NSString *mobileStr = [defaults objectForKey:@"phoneNumber"];
    //当前的app时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *locationTime=[dateformatter stringFromDate:senddate];
    
    //给服务器的字典
    NSMutableDictionary *lockBackDic = [NSMutableDictionary dictionary];
    [lockBackDic setObject:deeDataStr forKey:@"lockmessage"];
    [lockBackDic setObject:[self.currentOpenLockInfo objectForKey:@"uname"] forKey:@"uname"];
    [lockBackDic setObject:[self.currentOpenLockInfo objectForKey:@"id"] forKey:@"key_id"];
    [lockBackDic setObject:mobileStr forKey:@"mobile"];
    [lockBackDic setObject:locationTime forKey:@"apptime"];
    
    NSMutableArray *openlockinfor = [NSMutableArray array];
    
    [openlockinfor addObject:lockBackDic];
    NSLog(@"openlockinfor:%@",openlockinfor);
    
    //上传锁返回信息
    [KLHttpAPI uploadLockBackInfoToServer:openlockinfor completionHandler:^(NSDictionary *responseDic) {
        NSString *isSuccess = [responseDic objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            NSLog(@"开锁信息上传成功!");
        }
    } errorHandler:^(NSString *error) {
    }];
}

#pragma mark -上传开锁记录
-(void)saveOpenLockSuccessBackInformation:(NSData *)deeData{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //锁返回字符串
    NSString *deeDataStr = [deeData convertDataToHexStr:deeData];
    //用户手机号
    NSString *mobileStr = [defaults objectForKey:@"phoneNumber"];
    //当前的app时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYMMddHHmmss"];
    NSString *locationTime=[dateformatter stringFromDate:senddate];
    
    //给服务器的字典
    NSMutableDictionary *lockBackDic = [NSMutableDictionary dictionary];
    [lockBackDic setObject:deeDataStr forKey:@"lockmessage"];
    [lockBackDic setObject:[self.currentOpenLockInfo objectForKey:@"uname"] forKey:@"uname"];
    [lockBackDic setObject:[self.currentOpenLockInfo objectForKey:@"id"] forKey:@"key_id"];
    [lockBackDic setObject:mobileStr forKey:@"mobile"];
    [lockBackDic setObject:locationTime forKey:@"apptime"];
    
    [openLockSuccessInfo addObject:lockBackDic];
}

#pragma mark - 隐藏tabBar
- (void)hidesTabBar:(BOOL)hidden{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0];
    
    for (UIView *view in self.tabBarController.view.subviews) {
        if ([view isKindOfClass:[UITabBar class]]) {
            if (hidden) {
                [view setFrame:CGRectMake(view.frame.origin.x, [UIScreen mainScreen].bounds.size.height, view.frame.size.width , view.frame.size.height)];
            }else{
                [view setFrame:CGRectMake(view.frame.origin.x, [UIScreen mainScreen].bounds.size.height - 49, view.frame.size.width, view.frame.size.height)];
            }
        }else{
            if([view isKindOfClass:NSClassFromString(@"UITransitionView")]){
                if (hidden) {
                    [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, [UIScreen mainScreen].bounds.size.height)];
                }else{
                    [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, [UIScreen mainScreen].bounds.size.height - 49 )];
                }
            }
        }
    }
    [UIView commitAnimations];
}

#pragma mark - 手动开锁
-(void)searchPeripheral:(BOOL)scanOrStop{
    if(scanOrStop){
        [manager scanForPeripheralsWithServices:nil options:nil];
        isManaulOpen = YES;
    }else{
        [manager stopScan];
        isManaulOpen = NO;
    }
}

-(void)manualOpenLock:(NSInteger)row{
    _peripheral = self.manaulLocks[row];
    lockName = _peripheral.name;
    //    //开启开锁定时
    //    self.openTimeOut = [NSTimer scheduledTimerWithTimeInterval:12 target:self selector:@selector(openTimeOut:) userInfo:nil repeats:NO];
    //匹配钥匙
    if([self findKey]){
        //同时搜到钥匙即连接
        [manager connectPeripheral:_peripheral options:0];
    }
    //扫描到要连的设备即取消搜索超时并且停止扫描
    [manager stopScan];
}

#pragma mark - 监测蓝牙是否打开
-(void)chekBlueToothIsOpen{
    if(manager.state != 5){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"打开蓝牙来允许“KISSLOCK”连接到锁配件"
                                                        message:nil
                                               cancelButtonItem:[RIButtonItem itemWithLabel:@"设置" action:^{
            NSURL *url = [NSURL URLWithString:@"App-Prefs:root=Bluetooth"];//UIApplicationOpenSettingsURLString为跳往app设置
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];}
        }]
                                               otherButtonItems:[RIButtonItem itemWithLabel:@"好" action:^{
            [[NSUserDefaults standardUserDefaults] setBool:true forKey:@"canShark"];
        }], nil];
        
        [alert show];
    }
}

#pragma mark - 检测手动开锁扫到的设备是否有钥匙
-(BOOL)manaulIsHavekeyWithPeripheral:(CBPeripheral *)peripheral{
    //存入底层的锁主钥匙
    NSMutableArray *masterArr = [[NSUserDefaults standardUserDefaults] objectForKey:MASTER_KEY_ARRAY];
    //存入底层的子钥匙
    NSMutableArray *submitArr = [[NSUserDefaults standardUserDefaults] objectForKey:SUBMIT_KEY_ARRAY];
    BOOL haveKey = false;
    for (NSDictionary *keysDic in masterArr) {
        if([[keysDic objectForKey:@"uname"] isEqualToString:peripheral.name]){
            haveKey = true;
            break;
        }else
            haveKey = false;
    }
    if(haveKey == false){
        for (NSDictionary *keysDic in submitArr) {
            if([[keysDic objectForKey:@"uname"] isEqualToString:peripheral.name]){
                haveKey = true;
                break;
            }else{
                haveKey = false;
            }
        }
    }
    
    return haveKey;
}

//初始化左上角按钮
- (void)initLeftBarButtonItem {
    UIButton *lefrDrawerButton = [[UIButton alloc]init];
    lefrDrawerButton.backgroundColor = [UIColor clearColor];
    [lefrDrawerButton setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
    [lefrDrawerButton addTarget:self action:@selector(leftDrawerButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:lefrDrawerButton];
    [lefrDrawerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(45);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(20);
    }];
}-(void)leftDrawerButtonPress:(id)sender{//主页面的手势方法
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

//初始化右上角图标
-(void)initRightBarButtonItem {
    UIButton *rightDrawerButton = [[UIButton alloc]init];
    rightDrawerButton.backgroundColor = [UIColor clearColor];
    [rightDrawerButton setImage:[UIImage imageNamed:@"msg"] forState:UIControlStateNormal];
    [rightDrawerButton addTarget:self action:@selector(rightDrawerButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rightDrawerButton];
    [rightDrawerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(25);
        make.top.mas_equalTo(45);
    }];
    //小红点
    UIImageView *redPoint = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"红点图标"]];
    [self.view addSubview:redPoint];
    redPoint.layer.masksToBounds = YES;
    redPoint.layer.cornerRadius = 4;
    [redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(8);
        make.width.mas_equalTo(8);
        make.top.equalTo(rightDrawerButton).with.offset(-2);
        make.right.equalTo(rightDrawerButton).with.offset(2);
    }];
}-(void)rightDrawerButtonPress:(id)sender{//点击消息列表
    KLMessageTableViewController *messageVC = [[KLMessageTableViewController alloc]init];
    [self.navigationController pushViewController:messageVC animated:YES];
    [self hidesTabBar:YES];
}

#pragma mark - 封装顶部广告栏
-(void)initTheTopAdScrollView{
    //scrollView
    UIScrollView *topADView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 100)];
    topADView.backgroundColor = BB_White_Color;
    [topADView setContentSize:CGSizeMake(UI_View_Width*4, 100)];
    [topADView setPagingEnabled:YES];  //视图整页显示
    [topADView setBounces:YES]; //避免弹跳效果,避免把根视图露出来
    [self.view addSubview:topADView];
    //imageViews
    UIImageView *adImage1 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 100)];
    [adImage1 sd_setImageWithURL:[NSURL URLWithString:@"http://pic24.nipic.com/20121031/10144574_174119224000_2.jpg"] placeholderImage:[UIImage imageNamed:@"AD"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        adImage1.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapADImage:)];
        [adImage1 addGestureRecognizer:tap1];
    }];
    [topADView addSubview:adImage1];
    
    UIImageView *adImage2 = [[UIImageView alloc]initWithFrame:CGRectMake(UI_View_Width, 0, UI_View_Width, 100)];
    [adImage2 sd_setImageWithURL:[NSURL URLWithString:@"http://pic24.nipic.com/20121031/10144574_174119224000_2.jpg"] placeholderImage:[UIImage imageNamed:@"AD"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        adImage2.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapADImage:)];
        [adImage2 addGestureRecognizer:tap2];
    }];
    [topADView addSubview:adImage2];
    
    UIImageView *adImage3 = [[UIImageView alloc]initWithFrame:CGRectMake(UI_View_Width*2, 0, UI_View_Width, 100)];
    [adImage3 sd_setImageWithURL:[NSURL URLWithString:@"http://pic24.nipic.com/20121031/10144574_174119224000_2.jpg"] placeholderImage:[UIImage imageNamed:@"AD"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        adImage3.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapADImage:)];
        [adImage3 addGestureRecognizer:tap3];
    }];
    [topADView addSubview:adImage3];
    
    UIImageView *adImage4 = [[UIImageView alloc]initWithFrame:CGRectMake(UI_View_Width*3, 0, UI_View_Width, 100)];
    [adImage4 sd_setImageWithURL:[NSURL URLWithString:@"http://pic24.nipic.com/20121031/10144574_174119224000_2.jpg"] placeholderImage:[UIImage imageNamed:@"AD"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        adImage4.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap4 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapADImage:)];
        [adImage4 addGestureRecognizer:tap4];
    }];
    [topADView addSubview:adImage4];
}

-(void)tapADImage:(UITapGestureRecognizer *)tap{
    NSString *url = @"http://1a733381.atobo.com.cn";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

#pragma mark - 跟随手指移动的钥匙
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    bool canShark = [[NSUserDefaults standardUserDefaults] boolForKey:@"canShark"];
    if(!canShark){//如果正在执行开锁，则钥匙触摸无效
        self.keyImage.tag = 0;
        return ;
    }
    UITouch *touch = [touches anyObject];
    //当前的point
    CGPoint currentP = [touch locationInView:self.view];
    if(CGRectContainsPoint(self.keyImage.frame, currentP)){
        self.keyImage.tag = 1;
    }else{
        self.keyImage.tag = 0;
    }
}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //如果手指的初始位置不在图片上，则不可移动
    if(self.keyImage.tag == 0){
        return ;
    }
    UITouch *touch = [touches anyObject];
    //当前的point
    CGPoint currentP = [touch locationInView:self.view];
    //Y轴偏移的量
    CGFloat offsetY = currentP.y - self.lastP.y;
    //    CGFloat centerOffsetY = self.keyImage.center.y - self.lastP.y;
    NSLog(@"当前的:%f  原始的:%f  y轴的偏移量:%f",currentP.y,self.lastP.y,offsetY);
    if(offsetY >= -100 && offsetY <= 0){//如果偏移量超过100或者小于0，停止滑动
        self.keyImage.center = CGPointMake(self.lastP.x, self.lastP.y + offsetY);
        NSLog(@"正在滚动的距离:%f",offsetY);
    }else if(offsetY < -100){
        self.keyImage.center = CGPointMake(self.lastP.x, self.lastP.y - 100);
    }
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //如果手指的初始位置不在图片上，则不可移动
    if(self.keyImage.tag == 0){
        return ;
    }
    //    UITouch *touch = [touches anyObject];
    //当前的point
    //    CGPoint currentP = [touch locationInView:self.view];
    //Y轴偏移的量
    CGFloat offsetY = self.keyImage.center.y - self.lastP.y;
    NSLog(@"取消时的偏移量:%f",offsetY);
    if(offsetY > -100 && offsetY < 0){
        self.keyImage.center = self.lastP;
    }else if(offsetY <= -100){
        [self taplockOut];
    }
}

#pragma mark 5-17-锁厂锁开锁故障信息处理
- (void)messageOfTroubleData:(NSData *)troubleData deeData:(NSData *)deeDAta{
    
    MBProgressHUDManager *HUDManager = [[MBProgressHUDManager alloc] initWithView:[UIApplication sharedApplication].keyWindow];

    if (troubleData.length != 1) {
        return;
    }
    
    Byte msgByte[1];
    msgByte[0] = [troubleData byteFromData:troubleData];
    NSLog(@"转换后的byte：%hhu",msgByte[0]);
    // 1 失败， 0 成功
//    BOOL isUnlock = (msgByte[0] & 0x80) ? YES : NO;
//    BOOL isTimingSuccess = (msgByte[0] & 0x40) ? YES : NO;
//    BOOL ispwdSuccess = (msgByte[0] & 0x20) ? YES :NO;
    
    
    NSMutableString *msgStr = [NSMutableString string];
    
    if ((msgByte[0] & 0x80)) {
        // 开锁失败
       msgStr = @"开锁失败".mutableCopy;
        

        [self stop720Animation];
        //给服务器上传锁返回信息
        [self saveLockBackInformationForDictionary:deeDAta];
    }else {
        msgStr = @"开锁成功".mutableCopy;
    }
    
    if ((msgByte[0] & 0x40)) {
        
        msgStr = [NSMutableString stringWithFormat:@"%@校时间失败",msgStr];
        
        // 校时间失败
        [self stop720Animation];
        //给服务器上传锁返回信息
        [self saveLockBackInformationForDictionary:deeDAta];
    }
    

    if (msgByte[0] & 0x20){
        msgStr = [NSMutableString stringWithFormat:@"%@设置密码失败",msgStr];

        // 设置密码失败
        
        [self stop720Animation];
        //给服务器上传锁返回信息
        [self saveLockBackInformationForDictionary:deeDAta];
    }
    
    [HUDManager showSuccessWithMessage:msgStr duration:3];

//    [JRToast showWithText:msgStr];

}


@end
